import { HouseItem } from '@/types';

// 模拟延迟
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

// 生成模拟数据
const generateMockData = (): HouseItem[] => {
  const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都'];
  const communities = [
    '碧桂园',
    '万科城',
    '保利心语',
    '融创壹号院',
    '绿地中央广场',
    '恒大翡翠华庭',
    '龙湖天街',
    '中海国际社区',
  ];

  const data: HouseItem[] = [];

  for (let i = 1; i <= 85; i++) {
    const city = cities[Math.floor(Math.random() * cities.length)];
    const community =
      communities[Math.floor(Math.random() * communities.length)];
    const totalRooms = Math.floor(Math.random() * 4) + 2; // 2-5间
    const currentOccupied = Math.floor(Math.random() * (totalRooms + 1));
    const isFull = currentOccupied === totalRooms;

    // 随机决定是否有各项信息
    const hasPropertyInfo = Math.random() > 0.1; // 90% 有产权信息
    const hasAuthInfo = hasPropertyInfo && Math.random() > 0.15; // 85% 有核验信息
    const hasRentalInfo = hasAuthInfo && Math.random() > 0.2; // 80% 有出租信息
    const isExposed = hasRentalInfo && Math.random() > 0.3; // 70% 已曝光

    const baseRent = Math.floor(Math.random() * 3000) + 2000; // 2000-5000
    const actualRent = baseRent + Math.floor(Math.random() * 500);

    data.push({
      id: `house-${i.toString().padStart(3, '0')}`,
      cityName: city,
      communityName: community,
      address: `${city}市天河区${community}小区`,
      area: Math.floor(Math.random() * 50) + 80, // 80-130㎡
      occupancy: {
        current: currentOccupied,
        total: totalRooms,
      },
      monthlyRent: {
        actual: actualRent,
        base: baseRent,
      },
      contractAmount: Math.floor(Math.random() * 50000) + 30000, // 30000-80000
      serviceFee: Math.floor(Math.random() * 500) + 200, // 200-700
      signDate: `2023-${String(Math.floor(Math.random() * 12) + 1).padStart(
        2,
        '0',
      )}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      expireDate: `2024-${String(Math.floor(Math.random() * 12) + 1).padStart(
        2,
        '0',
      )}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      exposure: Math.floor(Math.random() * 5000),
      clicks: Math.floor(Math.random() * 1000),
      inquiries: Math.floor(Math.random() * 100),
      status: isFull ? 'full' : 'not_full',
      hasPropertyInfo,
      hasAuthInfo,
      hasRentalInfo,
      isExposed,
    });
  }

  return data;
};

let mockHouseData = generateMockData();

export default {
  // 获取房屋列表
  'GET /api/house/list': async (req: any, res: any) => {
    await waitTime(500);

    const {
      current = 1,
      pageSize = 10,
      tab = 'all',
      cityName,
      communityName,
      sortBy,
      order,
    } = req.query;

    console.log('Mock API - pageSize:', pageSize);
    console.log('Mock API - current:', current);

    let filteredData = [...mockHouseData];

    // 根据 tab 筛选
    if (tab === 'full') {
      filteredData = filteredData.filter((item) => item.status === 'full');
    } else if (tab === 'not_full') {
      filteredData = filteredData.filter((item) => item.status === 'not_full');
    }

    // 城市筛选
    if (cityName) {
      filteredData = filteredData.filter((item) =>
        item.cityName.includes(cityName),
      );
    }

    // 小区筛选
    if (communityName) {
      filteredData = filteredData.filter((item) =>
        item.communityName.includes(communityName),
      );
    }

    // 排序
    if (sortBy) {
      filteredData.sort((a: any, b: any) => {
        const aVal = a[sortBy];
        const bVal = b[sortBy];

        if (sortBy === 'monthlyRent') {
          const aRent = a.monthlyRent.actual;
          const bRent = b.monthlyRent.actual;
          return order === 'ascend' ? aRent - bRent : bRent - aRent;
        }

        if (typeof aVal === 'number' && typeof bVal === 'number') {
          return order === 'ascend' ? aVal - bVal : bVal - aVal;
        }

        if (typeof aVal === 'string' && typeof bVal === 'string') {
          return order === 'ascend'
            ? aVal.localeCompare(bVal)
            : bVal.localeCompare(aVal);
        }

        return 0;
      });
    }

    // 分页
    const start = (current - 1) * pageSize;
    const end = start + pageSize;
    const paginatedData = filteredData.slice(start, end);

    console.log('Mock API - start:', start, 'end:', end);
    console.log('Mock API - paginatedData length:', paginatedData.length);
    console.log('Mock API - total filtered:', filteredData.length);

    res.json({
      success: true,
      data: paginatedData,
      total: filteredData.length,
    });
  },

  // 曝光房屋
  'POST /api/house/expose': async (req: any, res: any) => {
    await waitTime(300);
    const { id } = req.body;

    const house = mockHouseData.find((item) => item.id === id);
    if (house) {
      house.isExposed = true;
      res.json({
        success: true,
        message: '曝光成功',
      });
    } else {
      res.status(404).json({
        success: false,
        message: '房屋不存在',
      });
    }
  },

  // 隐藏房屋
  'POST /api/house/hide': async (req: any, res: any) => {
    await waitTime(300);
    const { id } = req.body;

    const house = mockHouseData.find((item) => item.id === id);
    if (house) {
      house.isExposed = false;
      res.json({
        success: true,
        message: '隐藏成功',
      });
    } else {
      res.status(404).json({
        success: false,
        message: '房屋不存在',
      });
    }
  },
};
